﻿using STHPMS1.Common.C_Entity;
using STHPMS1.Common.C_Entity.Stmpms1;
using STHPMS1.ICore;
using STHPMS1.ICore.I_Core;
using STHPMS1.ICore.I_UI;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using System.IO;
using System.Reflection;
using Newtonsoft.Json;
using STHPMS1.ICore.I_Entity.Stmpms1;
using System.Collections.Generic;

namespace STHPMS1.Web.W_Controller
{
    [RoutePrefix("api/trfvolsurvey")]
    public class S_TrfvolsurveyPage1Controller : STHPMS1.Web.W_Core.MyController
    {
        [Route("")]
        [Route("page/{page?}", Name = "GettrfvolsurveyByPage")]
        [Route("rows/{rows?}")]
        [Route("page/{page?}/rows/{rows?}")]
        public IHttpActionResult Get(string rdwayid = null,int? direct=null,DateTime? checkDate = null, int page = 1, int rows = 10)
        {
            int p = page;
            int s = rows;

            PagingInfo info = new PagingInfo();
            info.PageIndex = p> 0 ? p - 1 : 0;
            info.PageSize = s;
            info.TotalRecords = 0;

            var data = this.Scene.Bll.S_Trfvolsurvey.GetByRoad(rdwayid,direct,checkDate, info);
            if (data == null) return NotFound();

            var result = new { rows = data, total = info.TotalRecords };

            return Ok(result);
        }

        [Route("")]
        public HttpResponseMessage Post(TrfvolsurveyModel entity)
        {
            HttpResponseMessage response = null;
            List<IS_Apply> applyList = new List<IS_Apply>();

            if (string.IsNullOrEmpty(entity.Applyid))
            {
                if (string.IsNullOrEmpty(entity.ApplyStake))
                {
                    response = Request.CreateResponse(HttpStatusCode.InternalServerError);
                    return response;
                }

                foreach (var item in entity.ApplyStake.Split(';'))
                {
                    if (string.IsNullOrEmpty(item)) continue;
                    string[] arr = item.Split(',');

                    S_Apply apply = new S_Apply();
                    apply.Appbeginmp = float.Parse(arr[1]);
                    apply.Appendmp = float.Parse(arr[2]);
                    apply.Apprdid = arr[0];
                    apply.Direction_Dictid = int.Parse(arr[3]);
                    apply.Applyid = this.Scene.Bll.S_Apply.SaveApply(apply);
                    applyList.Add(apply);


                    if (entity.His_Version == 0)
                        entity.His_Version = this.Scene.Bll.B_Roadway.GetNewHistoryVersion(apply.Apprdid, false);
                 
                    entity.Applyid = apply.Applyid;
                    entity.Importdate = DateTime.Now;
                    this.Scene.Bll.S_Trfvolsurvey.Save((S_Trfvolsurvey)entity);

                }
            }
            else
            {
                entity.Importdate = DateTime.Now;
                this.Scene.Bll.S_Trfvolsurvey.Save((S_Trfvolsurvey)entity);


                S_Apply apply = this.Scene.Dal.Sthpms1.SingleById<S_Apply>(entity.Applyid);
                applyList.Add(apply);
            }

            if (applyList.Count > 0)
                this.Scene.Bll.Dm_Trafaxle.CalacAxleLoadAndAge(applyList);

            response = Request.CreateResponse(HttpStatusCode.Created);
            // Generate a link to the new book and set the Location header in the response.
            string uri = Url.Link("GettrfvolsurveyByPage", new { page = 1 });
            response.Headers.Location = new Uri(uri);

            return response;
        }

        [Route("")]
        public void Delete(S_Trfvolsurvey entity)
        {
            this.Scene.Bll.S_Trfvolsurvey.Remove(entity);
        }

        [Route("gen")]
        public void GetAxleLoadAndAge()
        {
            this.Scene.Bll.Dm_Trafaxle.GenerateAxleLoadAndAge();
        }

        /// <summary>
        /// 上传数据处理
        /// </summary>
        /// <param name="file">文件路径</param>
        /// <param name="rdid">路线编号</param>
        /// <param name="bmp">起始桩号</param>
        /// <param name="emp">结束桩号</param>
        /// <param name="dir">方向</param>
        /// <returns></returns>
        [Route("saveFile")]
        public HttpResponseMessage PostSaveFile(string file)
        {         
            
            DataTable entity = null;//实体数据
            Excel_BaseImportData exData = null;//导入数据
            if (File.Exists(file))
            {
                try
                {
                    int startRow = 1;//Excel列头位置
                   
                        DataTable dt = Common.C_Excel.ExcelTool.RenderDataTableFromExcel(file, startRow);//获取Excel的DataTable
                        //验证Excel表头格式?

                        List<IS_Apply> applyList = new List<IS_Apply>();
                     //插入应用区间表
                        //foreach (var item in ApplyStake.Split(';'))
                        //{
                        //    if (string.IsNullOrEmpty(item)) continue;
                        //    string[] arr = item.Split(',');


                        //    S_Apply apply = new S_Apply();
                        //    apply.Appbeginmp = float.Parse(arr[1]);
                        //    apply.Appendmp = float.Parse(arr[2]);
                        //    apply.Apprdid = arr[0];
                        //    apply.Direction_Dictid = int.Parse(arr[3]);
                        //    apply.Applyid = this.Scene.Bll.S_Apply.SaveApply(apply); //保存并返回应用区间ID

                           

                        //    applyList.Add(apply);

                        //}
                        //一个应用区间ID对应交通量的数据
                            entity = GetData(dt, startRow, applyList);//将要导入的实体Table
                            exData = new Excel_BaseImportData(new S_Trfvolsurvey());//交通量实体
                            exData.DtSource = entity;
                            exData.TableName = "S_Trfvolsurvey"; //交通量实体 
                            //交通量的闭合性检查
                            

                            this.Scene.Bll.Excel.ImportData(exData); //导入数据

                        if (applyList.Count > 0)
                            this.Scene.Bll.Dm_Trafaxle.CalacAxleLoadAndAge(applyList);

                }
                catch (Exception ex)
                {
                    File.Delete(file);//删除上传数据
                    //抛出错误
                    var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content = new StringContent(ex.Message),
                        ReasonPhrase = "Server Error"
                    };
                    throw new HttpResponseException(response);
                }
                finally
                {
                    Common.C_Utils.MyCacheTools.ClearAllCache();
                }
            }
            else
            {
                //抛出错误
                var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent("服务器未能保存上传文件，请联系管理员"),
                    ReasonPhrase = "Server Error"
                };
                throw new HttpResponseException(response);
            }
            var res = Request.CreateResponse(HttpStatusCode.Created);
            string uri = Url.Link("GettrfvolsurveyByPage", new { page = 1 });
            res.Headers.Location = new Uri(uri);

            return res;
        }
        

        /// <summary>
        /// 反射获取对象的所有属性
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        private PropertyInfo[] GetAllProperty(object t)
        {
            Type temp = t.GetType();
            return temp.GetProperties();
        }
         /// <summary>
       /// 获取交通量的实体
       /// </summary>
       /// <param name="excel">导入的Excel</param>
       /// <param name="Rdwayid">路线编号</param>
       /// <param name="bmp">起始桩号</param>
       /// <param name="emp">结束桩号</param>
        ///<param name="startRow">提取位置</param>
        /// <param name="dir">方向</param>
       /// <returns></returns>
        private DataTable GetData(DataTable excel, int startRow, List<IS_Apply> applyList)
        {
            DataTable kh = new DataTable();
            PropertyInfo[] propertys = GetAllProperty(new S_Trfvolsurvey());
            foreach (PropertyInfo p in propertys)
            {
                kh.Columns.Add(new DataColumn(p.Name.ToUpper()));
            }
            kh.Columns.Add(new DataColumn("index")); //记录错误行号
            if (excel.Rows.Count == 0)
            {
                throw new Exception("Excel没有数据");
            }
            int index = startRow + 1;
            foreach (DataRow r in excel.Rows)
            {
               
                string _svydata = r[0].ToString();//观测时间
                string _STATNAME = r[1].ToString();//观测地点
                //string _DISSPLTPCT = r[2].ToString();//方向系数
                //string _LANECOEF = r[3].ToString();//车道
                string _TRUCK_S = r[2].ToString();//载重s
                string _TRUCK_M = r[3].ToString();//载重m
                string _TRUCK_L = r[4].ToString();//载重l
                string _TRUCK_O = r[5].ToString();//载重O
                string _CAR_S = r[6].ToString();//客车S
                string _CAR_L = r[7].ToString();//客车L
                string _ARTVEH = r[8].ToString();//拖挂
                string _CONTCAR = r[9].ToString();//集装箱
                string _TRACTOR = r[10].ToString();//拖拉机

                string rdid = r[11].ToString();//路线编号
                double start = Convert.ToDouble( r[12]);//起点
                double end = Convert.ToDouble(r[13]);//终点
                //验证路线和起终点桩号
                B_Roadway roads = GetRoad(rdid);
                //if (roads == null)
                //{
                //    throw new Exception("未能找到路线编号" + rdid);
                //}
                //else
                //{
                //    if (start < roads.Beginmp || end > roads.Endmp)
                //    {
                //        string msg = string.Format("路线{4}的起终点桩号超出实际桩号:Excel桩号[{0}-{1}],实际路线桩号[{2}-{3}]", start, end, roads.Beginmp, roads.Endmp, rdid);
                //        throw new Exception(msg);
                //    }
                //}
               
                //检查起点和终点桩号是否符合该路线的交通量划分标准
                this.Scene.Bll.B_Rdstandard.CheckMp(rdid, start,end);


                string dir_temp = r[14].ToString();//方向
                if (dir_temp == "全幅")
                {
                    //保存或修改应用区间表
                    S_Apply apply = new S_Apply();
                    apply.Appbeginmp = start;
                    apply.Appendmp = end;
                    apply.Apprdid = rdid;
                    apply.Direction_Dictid = (int)Common.C_Enum.DirectionEnum.All13;
                    apply.Applyid = this.Scene.Bll.S_Apply.SaveApplyBack(apply); //保存并返回应用区间ID
                    applyList.Add(apply);

                    DataRow dr = kh.NewRow();
                    dr["APPLYID"] = apply.Applyid; //应用区间ID
                    dr["OBVTM"] = _svydata;
                    dr["HIS_VERSION"] = this.Scene.Bll.B_Roadway.GetNewHistoryVersion(rdid);//版本号;//版本号
                    dr["STATNAME"] = _STATNAME;
                    //dr["DISSPLTPCT"] = _DISSPLTPCT == "" ? "0" : _DISSPLTPCT;
                    //dr["LANECOEF"] = _LANECOEF == "" ? "0" : _LANECOEF;
                    dr["TRUCK_S"] = _TRUCK_S == "" ? "0" : _TRUCK_S;
                    dr["TRUCK_M"] = _TRUCK_M == "" ? "0" : _TRUCK_M;
                    dr["TRUCK_L"] = _TRUCK_L == "" ? "0" : _TRUCK_L;
                    dr["TRUCK_O"] = _TRUCK_O == "" ? "0" : _TRUCK_O;
                    dr["CAR_S"] = _CAR_S == "" ? "0" : _CAR_S;
                    dr["CAR_L"] = _CAR_L == "" ? "0" : _CAR_L;
                    dr["ARTVEH"] = _ARTVEH == "" ? "0" : _ARTVEH;
                    dr["CONTCAR"] = _CONTCAR == "" ? "0" : _CONTCAR;
                    dr["TRACTOR"] = _TRACTOR == "" ? "0" : _TRACTOR;
                    dr["IMPORTDATE"] = DateTime.Now.ToShortDateString();
                    dr["index"] = index++;
                    kh.Rows.Add(dr);
                }
                else
                {
                    //上行
                    S_Apply apply = new S_Apply();
                    apply.Appbeginmp = start;
                    apply.Appendmp = end;
                    apply.Apprdid = rdid;
                    apply.Direction_Dictid = (int)Common.C_Enum.DirectionEnum.Up11;
                    apply.Applyid = this.Scene.Bll.S_Apply.SaveApplyBack(apply); //保存并返回应用区间ID
                    applyList.Add(apply);

                    DataRow dr = kh.NewRow();
                    dr["APPLYID"] = apply.Applyid; //应用区间ID
                    dr["OBVTM"] = _svydata;
                    dr["HIS_VERSION"] = this.Scene.Bll.B_Roadway.GetNewHistoryVersion(rdid);//版本号;//版本号
                    dr["STATNAME"] = _STATNAME;
                    //dr["DISSPLTPCT"] = _DISSPLTPCT == "" ? "0" : _DISSPLTPCT;
                    //dr["LANECOEF"] = _LANECOEF == "" ? "0" : _LANECOEF;
                    dr["TRUCK_S"] = _TRUCK_S == "" ? "0" : _TRUCK_S;
                    dr["TRUCK_M"] = _TRUCK_M == "" ? "0" : _TRUCK_M;
                    dr["TRUCK_L"] = _TRUCK_L == "" ? "0" : _TRUCK_L;
                    dr["TRUCK_O"] = _TRUCK_O == "" ? "0" : _TRUCK_O;
                    dr["CAR_S"] = _CAR_S == "" ? "0" : _CAR_S;
                    dr["CAR_L"] = _CAR_L == "" ? "0" : _CAR_L;
                    dr["ARTVEH"] = _ARTVEH == "" ? "0" : _ARTVEH;
                    dr["CONTCAR"] = _CONTCAR == "" ? "0" : _CONTCAR;
                    dr["TRACTOR"] = _TRACTOR == "" ? "0" : _TRACTOR;
                    dr["IMPORTDATE"] = DateTime.Now.ToShortDateString();
                    dr["index"] = index++;
                    kh.Rows.Add(dr);

                    //下行
                    apply = new S_Apply();
                    apply.Appbeginmp = start;
                    apply.Appendmp = end;
                    apply.Apprdid = rdid;
                    apply.Direction_Dictid = (int)Common.C_Enum.DirectionEnum.Down12;
                    apply.Applyid = this.Scene.Bll.S_Apply.SaveApplyBack(apply); //保存并返回应用区间ID
                    applyList.Add(apply);

                    dr = kh.NewRow();
                    dr["APPLYID"] = apply.Applyid; //应用区间ID
                    dr["OBVTM"] = _svydata;
                    dr["HIS_VERSION"] = this.Scene.Bll.B_Roadway.GetNewHistoryVersion(rdid);//版本号;//版本号
                    dr["STATNAME"] = _STATNAME;
                    //dr["DISSPLTPCT"] = _DISSPLTPCT == "" ? "0" : _DISSPLTPCT;
                    //dr["LANECOEF"] = _LANECOEF == "" ? "0" : _LANECOEF;
                    dr["TRUCK_S"] = _TRUCK_S == "" ? "0" : _TRUCK_S;
                    dr["TRUCK_M"] = _TRUCK_M == "" ? "0" : _TRUCK_M;
                    dr["TRUCK_L"] = _TRUCK_L == "" ? "0" : _TRUCK_L;
                    dr["TRUCK_O"] = _TRUCK_O == "" ? "0" : _TRUCK_O;
                    dr["CAR_S"] = _CAR_S == "" ? "0" : _CAR_S;
                    dr["CAR_L"] = _CAR_L == "" ? "0" : _CAR_L;
                    dr["ARTVEH"] = _ARTVEH == "" ? "0" : _ARTVEH;
                    dr["CONTCAR"] = _CONTCAR == "" ? "0" : _CONTCAR;
                    dr["TRACTOR"] = _TRACTOR == "" ? "0" : _TRACTOR;
                    dr["IMPORTDATE"] = DateTime.Now.ToShortDateString();
                    dr["index"] = index++;
                    kh.Rows.Add(dr);
                }

            }
            return kh;
        }


        [Route("uploadFile")]
        public void PostUploadFile()
        {
            
            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            string uploadPath =
              System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Upload") + "\\";
            string PhysicalPath = "";
            if (hfc.Count > 0)
            {
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                PhysicalPath = uploadPath + hfc[0].FileName;
                hfc[0].SaveAs(PhysicalPath);
            }

            System.Web.HttpContext.Current.Response.Write(PhysicalPath);
            System.Web.HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 路线信息
        /// </summary>
        /// <param name="stru_id"></param>
        /// <returns></returns>
        public B_Roadway GetRoad(string rdid)
        {
            List<B_Roadway> lst = null;
            if (!Common.C_Utils.MyCacheTools.IsCacheExist(rdid))
            {
                lst = this.Scene.Bll.B_Roadway.SearchById<B_Roadway>(rdid);
                Common.C_Utils.MyCacheTools.SetCache(rdid, lst, 24);
            }
            else
            {
                lst = Common.C_Utils.MyCacheTools.GetCache(rdid) as List<B_Roadway>;
            }
            if (lst.Count > 0)
                return lst[0];
            return null;
        }

    }


    public class TrfvolsurveyModel : S_Trfvolsurvey
    {
        public string ApplyStake { get; set; }
    }
}